package com.liujun.spring4.demo.aop.ioc.base.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * 使用反射机制进行操作目标类
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-09 07:08:00
 */
public class ReflectTest {

  /**
   * 进行初始化类的加载与调用
   *
   * @return 返回car对象
   * @throws Throwable
   */
  public static Car initByDefaultCoCnst() throws Throwable {
    // 1,通过类加载器获取Car类对象
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class clazz = loader.loadClass("com.liujun.spring4.demo.aop.ioc.base.reflect.Car");

    // 2,获取类的默认构造器对象并通过实例化Car
    Constructor cons = clazz.getDeclaredConstructor((Class[]) null);
    Car car = (Car) cons.newInstance();

    // 通过反射调用方法
    Method setBrondMethond = clazz.getMethod("setBrond", String.class);
    setBrondMethond.invoke(car, "红旗CA72");
    Method colorMethod = clazz.getMethod("setColor", String.class);
    colorMethod.invoke(car, "黑色");
    Method maxSpeed = clazz.getMethod("setMaxSpeed", int.class);
    maxSpeed.invoke(car, 200);
    return car;
  }

  public static void main(String[] args) throws Throwable {
    Car car = initByDefaultCoCnst();
    System.out.println(car.toString());
  }
}
